const db = uniCloud.database()

const state = {
  categories: [],
  loading: false
}

const mutations = {
  SET_CATEGORIES(state, categories) {
    state.categories = categories
  },
  SET_LOADING(state, status) {
    state.loading = status
  }
}

const actions = {
  async fetchCategories({ commit }) {
    commit('SET_LOADING', true)
    try {
      const { result } = await db.collection('opendb-news-categories')
        .field('name as text, _id')
        .get()
      commit('SET_CATEGORIES', result.data)
    } catch (error) {
      console.error('获取分类失败:', error)
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

const getters = {
  allCategories: state => state.categories,
  isLoading: state => state.loading
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}